<template>
  <div>
    <v-dialog v-model="dialog" max-width="500">
      <v-card>
        <v-card-title class="headline">Use Google's location service?</v-card-title>
        <v-progress-linear v-model="valueDeterminate"></v-progress-linear>
        <v-card-text>
          <div v-for="(item,i) in files" :key="i">{{item.name}}</div>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="grey" flat @click.native="dialog = false">{{$t('cancel')}}</v-btn>
          <v-btn color="secondary darken-1" flat @click.native="upload">{{$t('sure')}}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-card>
      <v-list subheader two-line>
        <v-subheader>
          <span class="title">所有文件</span>
          <v-spacer></v-spacer>
          <v-btn v-if="enableManage" @click="openUpload" color="primary">{{$t('upload')}}<v-icon right dark>cloud_upload</v-icon></v-btn>
          <input type="file" style="display: none" ref="assets" name="assets" id="assets" @change="handleUpload" multiple />
        </v-subheader>
        <template v-for="item in items">
          <v-divider></v-divider>
          <v-list-tile avatar :key="item._id">
            <v-list-tile-avatar>
              <v-icon :style="{ color: iconColor[ext(item.ext)]}">{{item.ext | ext}}</v-icon>
            </v-list-tile-avatar>
            <v-list-tile-content>
              <v-list-tile-title>{{item.name}}</v-list-tile-title>
              <v-list-tile-sub-title>{{item.download_times + $t('downloads')}}, {{item.created_at | formatTime}}上传</v-list-tile-sub-title>
            </v-list-tile-content>
            <v-list-tile-action>
              <v-btn icon @click="handleDownload(item._id)">
                <v-icon color="secondary">file_download</v-icon>
              </v-btn>
              <v-btn icon @click="handleDelete(item._id)" v-if="enableManage">
                <v-icon color="error">delete</v-icon>
              </v-btn>
            </v-list-tile-action>
          </v-list-tile>
        </template>
      </v-list>
    </v-card>
  </div>
</template>

<script>
import axios from 'axios'
import * as resourcesApi from '@/api/resource'
import { ext } from '@/filters'
export default {
  data: () => ({
    dialog: false,
    files: [],
    valueDeterminate: 0,
    items: [],
    iconColor: {
      'fas fa-image': '#F06292',
      'fas fa-file-excel': '#22734a',
      'fas fa-file-word': '#2a5699',
      'fas fa-file-pdf': '#da1f00',
      'fas fa-file-alt': '#b2b2b4',
      'fas fa-file-archive': '#7eb978'
    }
  }),
  created() {
    resourcesApi.fetchResources(this.$store.getters.team).then(res => {
      this.items = res.data.items
    })
  },
  computed: {
    enableManage() {
      return this.$store.getters.roles.some(v => (v === 'admin' || v === 'resource'))
    }
  },
  methods: {
    ext,
    handleDownload(id) {
      window.open(`/resources/${id}`)
    },
    handleDelete(id) {
      resourcesApi.deleteResource(id).then(res => {
        if (res.status === 204) {
          for (const item of this.items) {
            if (item._id === id) {
              const index = this.items.indexOf(item)
              this.items.splice(index, 1)
              break
            }
          }
          this.$notify.success('删除成功')
        } else {
          this.$notify.error('删除失败')
        }
      })
    },
    handleUpload(e) {
      this.files = e.target.files
      if (this.files.length > 5) this.$notify.warning('最大上传上限为5个文件')
      else if (this.files.length < 1) this.$notify.warning('至少选择一个文件')
      else this.dialog = true
    },
    openUpload() {
      document.getElementById('assets').click()
    },
    upload() {
      const form = new FormData()
      for (let i = 0; i < this.files.length; i++) {
        form.append('assets', this.files[i])
      }
      axios.put('/resources', form, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        transformRequest: [function(data) { return data }],
        onUploadProgress: e => {
          this.valueDeterminate = Math.round((e.loaded * 100) / e.total) || 0
        }
      }).then(res => {
        if (res.status === 200) {
          this.items = res.data.saved.concat(this.items)
          this.$notify.success('上传成功')
        } else {
          this.$notify.error('上传失败')
        }
        this.dialog = false
        this.valueDeterminate = 0
      })
    }
  }
}
</script>

<style scoped>

</style>
